//
// Source code recreated from a .class file by IntelliJ IDEA
// (powered by FernFlower decompiler)
//

package com.example.photograph.utils;


import java.io.OutputStream;
import java.lang.reflect.Field;
import java.lang.reflect.Method;
import java.math.BigDecimal;
import java.net.URLEncoder;
import java.text.SimpleDateFormat;
import java.util.ArrayList;
import java.util.Date;
import java.util.Iterator;
import java.util.List;
import java.util.Map;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import com.example.photograph.exception.BusinessException;
import org.apache.poi.hssf.usermodel.HSSFWorkbook;
import org.apache.poi.ss.usermodel.Cell;
import org.apache.poi.ss.usermodel.DateUtil;
import org.apache.poi.ss.usermodel.Row;
import org.apache.poi.ss.usermodel.Sheet;
import org.apache.poi.ss.usermodel.Workbook;
import org.apache.poi.xssf.usermodel.XSSFWorkbook;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.web.multipart.MultipartFile;

public class ExcelUtils {
    private static Logger log = LoggerFactory.getLogger(ExcelUtils.class);
    private static final String XLS = ".xls";
    private static final String XLSX = ".xlsx";
    private static final String FIREFOX = "firefox";

    public ExcelUtils() {
    }

    public static <T> void exportExcel(List<T> list, String[] headers, String[] columns, HttpServletRequest request, HttpServletResponse response, String fileName) {
        try {
            Workbook workbook = null;
            if (fileName.endsWith(".xls")) {
                workbook = new HSSFWorkbook();
            } else if (fileName.endsWith(".xlsx")) {
                workbook = new XSSFWorkbook();
            } else {
                fileName = fileName + ".xlsx";
                workbook = new XSSFWorkbook();
            }

            Sheet sheet = ((Workbook)workbook).createSheet();
            Row row = sheet.createRow(0);

            Cell cell;
            int index;
            for(index = 0; index < headers.length; ++index) {
                cell = row.createCell(index);
                cell.setCellValue(headers[index]);
            }

            index = 1;
            Iterator<T> var11 = list.iterator();

            while(var11.hasNext()) {
                T t = var11.next();
                row = sheet.createRow(index);
                ++index;

                for(short i = 0; i < columns.length; ++i) {
                    cell = row.createCell(i);
                    String fieldName = columns[i];
                    Object value = null;
                    Map map = null;
                    String textValue;
                    if (t instanceof Map) {
                        map = (Map)t;
                        value = map.get(fieldName);
                    } else {
                        textValue = "get" + fieldName.substring(0, 1).toUpperCase() + fieldName.substring(1);
                        Class tCls = t.getClass();
                        Method getMethod = tCls.getMethod(textValue);
                        value = getMethod.invoke(t);
                    }

                    textValue = null;
                    if (value == null) {
                        textValue = "";
                    } else if (value instanceof Date) {
                        SimpleDateFormat formatter = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
                        textValue = formatter.format(value);
                    } else {
                        textValue = value.toString();
                    }

                    cell.setCellValue(textValue);
                }
            }

            String userAgent = request.getHeader("USER-AGENT").toLowerCase();
            if (userAgent.contains("firefox")) {
                fileName = new String(fileName.getBytes(), "iso-8859-1");
            } else {
                fileName = URLEncoder.encode(fileName, "UTF8");
            }
            OutputStream ouputStream = response.getOutputStream();
            response.setContentType("application/vnd.ms-excel");
            response.setHeader("Content-disposition", "attachment;filename=" + fileName);
            response.setHeader("Pragma", "No-cache");

            ((Workbook)workbook).write(ouputStream);
            // ouputStream.flush();
            // ouputStream.close();
            workbook.close();
        } catch (Exception var20) {
            throw new BusinessException("导出Excel异常");
        }
    }

    public static <T> List<T> importExcel(MultipartFile multipartFile, Class<T> clazz, String[] columns) throws Exception {
        List<T> result = new ArrayList();
        Workbook workbook = getWorkbook(multipartFile);

        try {
            for(int sheetNum = 0; sheetNum < workbook.getNumberOfSheets(); ++sheetNum) {
                Sheet sheet = workbook.getSheetAt(sheetNum);
                if (sheet != null) {
                    for(int rowNum = 1; rowNum <= sheet.getLastRowNum(); ++rowNum) {
                        Row row = sheet.getRow(rowNum);
                        if (row != null) {
                            T object = clazz.newInstance();

                            for(int cellNum = 0; cellNum < columns.length; ++cellNum) {
                                Cell cell = row.getCell(cellNum);
                                String value = getCellValue(cell);
                                String fieldName = columns[cellNum];
                                Field[] fields = clazz.getDeclaredFields();
                                Field[] var15 = fields;
                                int var16 = fields.length;

                                for(int var17 = 0; var17 < var16; ++var17) {
                                    Field field = var15[var17];
                                    String name = field.getName();
                                    if (fieldName.equals(name)) {
                                        String setFieldName = "set" + fieldName.substring(0, 1).toUpperCase() + fieldName.substring(1);
                                        Method method = clazz.getMethod(setFieldName, field.getType());
                                        if (field.getType() == String.class) {
                                            method.invoke(object, value);
                                        } else if (field.getType() == Integer.class) {
                                            method.invoke(object, Integer.valueOf(value));
                                        } else if (field.getType() == Date.class) {
                                            method.invoke(object, new Date());
                                        } else {
                                            log.info("未赋值==={}", setFieldName);
                                        }
                                    }
                                }
                            }

                            result.add(object);
                        }
                    }
                }
            }

            return result;
        } catch (Exception var22) {
            log.error("异常==={}", var22);
            throw new BusinessException("解析Excel异常");
        }
    }

    public static Workbook getWorkbook(MultipartFile multipartFile) throws Exception {
        String fileName = multipartFile.getOriginalFilename();
        if (fileName != null && !"".equals(fileName)) {
            Object workbook;
            if (fileName.endsWith(".xls")) {
                workbook = new HSSFWorkbook(multipartFile.getInputStream());
            } else {
                if (!fileName.endsWith(".xlsx")) {
                    throw new BusinessException("文件格式不支持");
                }

                workbook = new XSSFWorkbook(multipartFile.getInputStream());
            }

            return (Workbook)workbook;
        } else {
            throw new BusinessException("请上传文件");
        }
    }

    public static String getCellValue(Cell cell) {
        int ordinal = cell.getCellType().ordinal();
        switch(ordinal) {
        case 1:
            short format = cell.getCellStyle().getDataFormat();
            boolean flag = format == 14 || format == 31 || format == 57 || format == 58 || 176 <= format && format <= 178 || 182 <= format && format <= 196 || 210 <= format && format <= 213 || 208 == format;
            if (flag) {
                double value = cell.getNumericCellValue();
                Date date = DateUtil.getJavaDate(value);
                SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd");
                return sdf.format(date);
            } else {
                return (new BigDecimal(cell.getNumericCellValue())).stripTrailingZeros().toPlainString();
            }
        case 2:
            return cell.getStringCellValue();
        case 3:
            return cell.getCellFormula();
        case 4:
            return String.valueOf(cell.getBooleanCellValue());
        default:
            return "";
        }
    }
}